package demo.thread;

public class TimeWaitingTest {

    public static void main(String[] args) {
        try {
            ThreadTest();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void ThreadTest() throws InterruptedException {
        Thread mainThread = Thread.currentThread();

        Thread threadB = new Thread(new Runnable() {
            @Override
            public void run() {
                testMethod();
            }
        }, "ThreadB");

        Thread threadA = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(mainThread.getName() + ": [" + mainThread.getState() + "]");
                System.out.println(threadB.getName() + ": [" + threadB.getState() + "]");
                System.out.println("******************************");
                testMethod();
            }
        }, "ThreadA");

        System.out.println(mainThread.getName() + ": [" + mainThread.getState() + "]");
        System.out.println(threadA.getName() + ": [" + threadA.getState() + "]");
        System.out.println(threadB.getName() + ": [" + threadB.getState() + "]");
        System.out.println("==============================");


        threadA.start();
        // threadA 线程执行 500ms，使当前线程 main 线程进入 TIMED_WAITING 状态
        threadA.join(500L);
        threadB.start();

        System.out.println(mainThread.getName() + ": [" + mainThread.getState() + "]");
        System.out.println(threadA.getName() + ": [" + threadA.getState() + "]");
        System.out.println(threadB.getName() + ": [" + threadB.getState() + "]");
        System.out.println("==============================");

        Thread.sleep(5000L);
        System.out.println("==============================");
        System.out.println(threadA.getName() + ": [" + threadA.getState() + "]");
        System.out.println(threadB.getName() + ": [" + threadB.getState() + "]");
    }

    // 同步方法争夺锁
    private static synchronized void testMethod() {
        try {
            Thread.sleep(2000L);
            Thread thread = Thread.currentThread();
            System.out.println("Hello from " + thread.getName() + ": [" + thread.getState() + "]");
            System.out.println("***========================***");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
